import 'dart:io';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';

class PhotoViewSimpleScreen extends StatefulWidget {
  final ImageProvider? imageProvider; //图片
  final BoxDecoration? backgroundDecoration; //背景修饰
  final dynamic minScale; //最大缩放倍数
  final dynamic maxScale; //最小缩放倍数
  final String? heroTag; //hero动画tagid
  final String? imageUrl; //图片地址
  PhotoViewSimpleScreen({
    Key? key,
    required this.imageProvider,
    this.imageUrl,
    this.backgroundDecoration,
    this.minScale = 1.0,
    this.maxScale = 1.0,
    this.heroTag,
  }) : super(key: key);

  @override
  _PhotoViewSimpleScreenState createState() => _PhotoViewSimpleScreenState();
}

class _PhotoViewSimpleScreenState extends State<PhotoViewSimpleScreen> {
  @override
  void initState() {
    super.initState();
    _requestPermission();
  }

  //检查权限
  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
    // _toastInfo(info);
  }

  _toastInfo(String info) {
    Fluttertoast.showToast(msg: info, toastLength: Toast.LENGTH_LONG);
  }

  _saveScreen(String url) async {
    // 这个图片的地址是本地的文件进行测试 要引入,import 'package:flutter/services.dart' show rootBundle;
    // ByteData bytes = await rootBundle.load('assets/images/guide3.png');
    // final result = await ImageGallerySaver.save(bytes.buffer.asUint8List()); //这个是核心的保存图片的插件

    var response = await Dio()
        .get(url, options: Options(responseType: ResponseType.bytes));
    final result =
        await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    // 判断ios还是android,故需要引入 import 'dart:io';
    if (Platform.isIOS) {
      if (result) {
        Fluttertoast.showToast(msg: '成功保存到相册中');
      } else {
        Fluttertoast.showToast(msg: '保存失败');
      }
    } else {
      if (result != null) {
        Fluttertoast.showToast(msg: '成功保存到相册中');
      } else {
        Fluttertoast.showToast(msg: '保存失败');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        constraints: BoxConstraints.expand(
          height: MediaQuery.of(context).size.height,
        ),
        child: Stack(
          children: <Widget>[
            Positioned(
              top: 0,
              left: 0,
              bottom: 0,
              right: 0,
              child: PhotoView(
                imageProvider: CachedNetworkImageProvider(
                  widget.imageUrl ??
                      'https://amoy-ticket.oss-cn-nanjing.aliyuncs.com/images/people/dog.jpg',
                ),
                backgroundDecoration: widget.backgroundDecoration,
                minScale: 0.8,
                maxScale: 2.0,
                // initialScale: 1.0,
                heroAttributes:
                    PhotoViewHeroAttributes(tag: widget.heroTag ?? ''),
                enableRotation: false,
                filterQuality: FilterQuality.medium,
              ),
            ),
            Positioned(
              //右上角关闭按钮
              right: 10,
              top: MediaQuery.of(context).padding.top,
              child: IconButton(
                icon: Icon(
                  Icons.close,
                  size: 30,
                  color: Colors.white,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ),
            Positioned(
              //左下角保存图片
              bottom: MediaQuery.of(context).padding.bottom + 16,
              child: TextButton(
                child: Text(
                  '保存图片',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
                onPressed: () {
                  _saveScreen(widget.imageUrl ?? '');
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}
